﻿/// <reference path="/Scripts/jquery-1.5.1.js"/>

$(function () {
    function split_chapters(patternRe, content) {
        var chapterTitlePositions = [];
        var m;
        while ((m = patternRe.exec(content)) != null) {
            chapterTitlePositions.push({ start: m.index, end: m.index + m[0].length });
        }
        if (chapterTitlePositions.length == 0) {
            $("#process-error-message").text("Can't find any splitter");
            return;
        }
        var chapters = [];
        for (var i = 0; i < chapterTitlePositions.length; i++) {
            chapters.push({
                title: $.trim(content.substring(chapterTitlePositions[i].start, chapterTitlePositions[i].end)),
                content: content.substring(chapterTitlePositions[i].end,
                                           (i < chapterTitlePositions.length - 1) ?
                                                chapterTitlePositions[i + 1].start :
                                                content.length)
            });
        }
        return chapters;
    }

    function populate_result_box(chapters) {
        var resultBox = $("#result-chapter-list");
        resultBox.children().remove();
        resultBox.data("chapters", chapters);

        $.each(chapters, function (i, ch) {
            $("<option></option").text(ch.title)
                                 .data("chapter", ch)
                                 .appendTo(resultBox);
        });
        resultBox.change();
    }

    services_plaintext = {
        create_re: function (pattern) {
            return new RegExp("^\\s*" + pattern + "\\s*$", "gm");
        },
        get_volume_content: function () {
            return $.trim($("#volume-content").val());
        },
        content_need_sanitizing: function () {
            return ($("#preprocess-text:checked").length > 0);
        },
        sanitize_title: function (title) {
            return title.replace(/^#+/, "");
        },
        sanitize_content: function (text) {
            return $.trim(text).replace(/^.*$/mg, function (s) {
                s = $.trim(s);
                s = $("<div></div>").text(s).html();
                s = s || "&nbsp;";
                return "<p>" + s + "</p>";
            });
        }
    };

    services_richtext = {
        create_re: function (pattern) {
            return new RegExp("^(\\s|&nbsp;)*(<.+?>)*(\\s|&nbsp;)*" + pattern + "(\\s|&nbsp;)*(<.+?>)*(\\s|&nbsp;)*$", "gm");
        },
        get_volume_content: function () {
            return $("#volume-content").tinymce().getContent();
        },
        content_need_sanitizing: function () {
            return true;
        },
        sanitize_title: function (title) {
            return $.trim($("<div></div>").html(title).text()
                        .replace(/^\s*#+\s*/g, "")
                        .replace(/\s+/g, " "));
        },
        sanitize_content: function (text) {
            return text.replace(/^\s*(<p>&nbsp;<\/p>\s*)+|(\s*<p>&nbsp;<\/p>)+\s*$/gi, "");
        }
    };

    if (window["enable_richtext"]) {
        services = services_richtext;
    } else {
        services = services_plaintext;
    }

    $("#predefined-patterns").change(function () {
        var selected = $("option:selected", this);
        if ($("option", this).index(selected) > 0) {
            $("#split-pattern").val(selected.text());
        }
    });
    $("#process-button").click(function (e) {
        e.preventDefault();
        $("#process-error-message").text("");
        var content = $.trim($("#volume-content").val());
        if (!content) {
            $("#process-error-message").text("Volume content is empty");
            return;
        }
        var pattern = $.trim($("#split-pattern").val());
        if (!pattern) {
            $("#process-error-message").text("Split pattern is empty");
            return;
        }

        var patternRe = services.create_re(pattern);
        var chapters = split_chapters(patternRe, content);
        if (!chapters) {
            return;
        }

        if (services.content_need_sanitizing()) {
            $.each(chapters, function (i, ch) {
                ch.title = services.sanitize_title(ch.title);
                ch.content = services.sanitize_content(ch.content);
            });
        }
        populate_result_box(chapters);
        return false;
    });
    $("#result-chapter-list").change(function () {
        var ch = $("option:selected", this).data("chapter");
        $("#result-chapter-preview-name").val(ch ? ch.title : "");
        $("#result-chapter-preview-content").val(ch ? ch.content : "");
    });
    $("#result-chapter-preview-name").change(function () {
        var selected = $("#result-chapter-list option:selected");
        if (selected) {
            var ch = selected.data("chapter");
            ch.title = $(this).val();
            selected.text(ch.title);
        }
    });
    $("#result-chapter-preview-content").change(function () {
        var selected = $("#result-chapter-list option:selected");
        if (selected) {
            var ch = selected.data("chapter");
            ch.content = $(this).val();
        }
    });
    $("#submit-button").click(function (e) {
        e.preventDefault();
        var data = $("#result-chapter-list").data("chapters");
        if (!data) {
            $("#submit-error-message").text("No chapter is added.");
            return false;
        }
        $("#submit-error-message").text("");
        var button = $(this);
        button.attr("disabled", "disabled");
        $.ajax({
            type: "POST",
            dataType: "json",
            data: JSON.stringify({ chapters: $.map(data, function (ch) {
                return {
                    Name: ch.title,
                    NovelVolumeId: $("[name=NovelVolumeId]").val(),
                    PostUserName: $("[name=PostUserName]").val(),
                    ChapterContent: ch.content
                };
            })
            }),
            contentType: "application/json; charset=utf-8",
            complete: function () {
                button.attr("disabled", null);
            },
            success: function (resp) {
                if (resp.error) {
                    $("#submit-error-message").text(resp.error);
                } else {
                    location.href = resp.redirectTo;
                }
            },
            error: function (xhr, status) {
                $("#submit-error-message").text(status);
            }
        });
        return false;
    });
});